import React, { PureComponent, Fragment } from 'react'
import { connect } from 'dva'
import {
  Button,
  Input,
  Spin,
  Form,
  Row,
  Col,
  Select,
  Upload,
  Icon,
  Radio,
  Card,
  Modal,
  message,
  Tabs,
  Popconfirm,
  Table
} from 'antd'
const { TabPane } = Tabs
import 'braft-editor/dist/index.css'
import BraftEditor from 'braft-editor'
import { routerRedux } from 'dva/router'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { LZFormItem } from '@/components/LZForm'
import commonApi from '@/services/common'
import TribeApi from '@/services/tribe'
import { getToken } from '@/utils/localStorage'
import { isEqual } from 'lodash'
import RouterWillLeave from '@/components/RouterWillLeave'
import CustomCard from '@/components/CustomCard'
import ActivityServices from './services'
import CopyToClipboard from '@/components/CopyToClipboard'
import { bfUploadFn } from '@/utils/utils'
import index from '@/components/Frame'
const FormItem = Form.Item
const formItemLayout = {
  labelCol: {
    span: 4
  },
  wrapperCol: {
    span: 12
  }
}
const formItemLayoutModal = {
  labelCol: {
    span: 6
  },
  wrapperCol: {
    span: 18
  }
}
let id = 1

@connect()
@Form.create()
class Publish extends PureComponent {
  state = {
    imgSrc: '',
    picUrl: '',
    platforms: [],
    detail: {},
    visible: false,
    updateId: 0,
    fileList: [],
    id: '',
    images: [],
    isSubmit: false,
    originValues: {},
    activityTableList: [],
    tableName: undefined,
    tabKa: 0,
    title: '',
    list: [],
    total: 1,
    selectedRows: [],
    keyWord: undefined,
    pageNumber: 1,
    visibleCommodity: false,
    selectedRowsListData: [],
    data: {},
    add: ['']
  }

  componentDidMount() {
    const {
      match: {
        params: { id }
      }
    } = this.props
    let _id = id
    const {
      form: { getFieldDecorator, getFieldValue }
    } = this.props
    if (_id) {
      ActivityServices.queryActivityDetail({ id: _id }).then(res => {
        this.setState({
          data: res,
          activityTableList: res.activityTableList,
          add: res.carouselList.length ? res.carouselList : [''],
          id: _id
        })
      })
    }
    this.onList(1, 10)
  }
  onList = (pageNumber, pageSize, keyWord) => {
    ActivityServices.ableProductV1({ pageNumber, pageSize, keyWord }).then(
      res => {
        this.setState({
          list: res.records,
          total: res.total
        })
      }
    )
  }
  onChange = pageNumber => {
    this.setState(
      {
        pageNumber
      },
      () => {
        this.onList(pageNumber, 10, this.state.keyWord)
      }
    )
  }
  // 查询
  search = () => {
    this.setState(
      {
        pageNumber: 1
      },
      () => {
        this.onList(this.state.pageNumber, 10, this.state.keyWord)
      }
    )
  }

  handleSetOriginValues = () => {
    const values = this.props.form.getFieldsValue()
    this.setState({
      originValues: values
    })
  }

  getPlatformChannel = () => {
    commonApi.selectPlateformChannel().then(res => {
      this.setState({
        platforms: res
      })
    })
  }

  handleSubmit = e => {
    const { form, dispatch } = this.props
    const { id, images, detail } = this.state
    e.preventDefault()

    form.validateFieldsAndScroll({ force: true }, (err, fieldsValue) => {
      fieldsValue.activityDescription = fieldsValue.activityDescription.toHTML()
      if (!fieldsValue.tofuCubes[0]) {
        fieldsValue.tofuCubes = null
      }

      if (id) {
        ActivityServices.modifyActivity({
          ...fieldsValue,
          carouselList: this.state.add[0] ? this.state.add : null,
          id,
          activityTableList: this.state.activityTableList
        }).then(res => {
          message.success('修改成功。')
          dispatch(routerRedux.push('/configure/Activity/index'))
        })
      } else {
        ActivityServices.addActivity({
          ...fieldsValue,
          carouselList: this.state.add[0] ? this.state.add : null,
          activityTableList: this.state.activityTableList
        }).then(res => {
          message.success('新增成功。')
          dispatch(routerRedux.push('/configure/Activity/index'))
        })
      }
    })
  }

  handleCancel = () => {
    const { dispatch } = this.props
    dispatch(routerRedux.push('/configure/Activity/index'))
  }

  handleChangeInitialValue = (evt, field) => {
    this.setState({
      detail: {
        ...this.state.detail,
        [field]: evt.target.value
      }
    })
  }

  handleUploadChange = ({ file, fileList, event }, type) => {
    const _fileList = [...fileList] || []
    if (type === 'picUrl') {
      if (file.status === 'done') {
        _fileList.map(item => {
          this.setState({
            picUrl: item.response.data
          })
        })
        this.setState({
          picUrl: file.response.data
        })
      }
    } else {
      if (file.status === 'done') {
        const images = _fileList.map(f => {
          return {
            isMain: 0,
            src: f.response.data
          }
        })
        this.setState({
          images
        })
      }
      this.setState({
        fileList: _fileList
      })
    }
  }

  // 上传后预览的回调
  handlePreview = e => {
    if (e === '修改') {
      if (this.state.activityTableList.length) {
        this.setState({
          visible: true,
          title: e
        })
      }
    } else {
      this.setState({
        visible: true,
        title: e
      })
    }
  }

  handlePreviewCommodity = () => {
    this.setState({
      visibleCommodity: true
    })
  }
  handleCancelCommodity = () => {
    this.setState({
      visibleCommodity: false
    })
  }
  submit = () => {
    let { selectedRows, selectedRowsListData, tabKa } = this.state
    let _activityTableList = this.state.activityTableList
    let typetabKa =
      typeof tabKa === 'string' ? parseInt(tabKa.split('/')[0]) : tabKa
    let selectedRowsList = selectedRows
    if (selectedRowsList.length === 0) {
      message.warning('请选择商品。')
    } else {
      selectedRowsList.forEach(item => {
        _activityTableList[typetabKa].activityProductDtoList.push(item)
      })
      this.setState({
        activityTableList: _activityTableList,
        visibleCommodity: false
      })
    }
  }
  handleImgCancel = () => {
    this.setState({
      visible: false
    })
  }

  // 上传后删除的回调
  onRemove = type => {
    if (type === 'picUrl') {
      this.setState({
        picUrl: ''
      })
    } else {
      this.setState({
        fileList: [],
        imgSrc: ''
      })
    }
  }

  renderRouterWillLeave = () => {
    const values = this.props.form.getFieldsValue()
    const { originValues, isSubmit } = this.state
    const isPrompt = !isEqual(values, originValues)
    return <RouterWillLeave isPrompt={isPrompt} isSubmit={isSubmit} />
  }
  add = () => {
    const { form } = this.props
    const keys = form.getFieldValue('keys')
    if (keys.length > 4) {
      message.warning('最多添加5个。')
      return
    }
    const nextKeys = keys.concat(id++)
    form.setFieldsValue({
      keys: nextKeys
    })
  }
  remove = k => {
    let _add = [...this.state.add]

    _add.splice(k, 1)
    this.setState({
      add: _add
    })
  }
  callback = e => {
    this.setState({
      tabKa: e
    })
  }
  onDelet = () => {
    let activityTableListss = this.state.activityTableList
    let tabKaJ = this.state.tabKa
    let typetabKa =
      typeof tabKaJ === 'string' ? parseInt(tabKaJ.split('/')[0]) : tabKaJ
    activityTableListss.splice(typetabKa, 1)
    if (typetabKa > 0 && activityTableListss.length != typetabKa) {
      this.setState(
        {
          activityTableList: activityTableListss,
          tabKa: tabKaJ
        },
        () => {
          this.callback(`${tabKaJ}/${Math.random()}`)
        }
      )
      return
    }
    if (tabKaJ === 0) {
      this.setState(
        {
          activityTableList: activityTableListss,
          tabKa: 1
        },
        () => {
          this.callback(0)
        }
      )
    } else {
      this.setState(
        {
          activityTableList: activityTableListss,
          tabKa: 0
        },
        () => {
          this.callback(0)
        }
      )
    }
  }
  // 查询的
  handleKeyWords = e => {
    this.setState({
      keyWord: e.target.value
    })
  }
  showTotal = () => {
    return `共有${this.state.total}条`
  }
  onDeletChild = e => {
    const { tabKa } = this.state
    let _activityTableList = [...this.state.activityTableList]
    let typetabKa =
      typeof tabKa === 'string' ? parseInt(tabKa.split('/')[0]) : tabKa
    _activityTableList[typetabKa].activityProductDtoList.splice(e, 1)
    this.setState({
      activityTableList: _activityTableList
    })
  }
  onOk = e => {
    e.preventDefault()
    this.props.form.validateFields(['remark'], (err, value) => {
      if (!err) {
        let activityTableLists = this.state.activityTableList
        if (this.state.title === '修改') {
          if (typeof this.state.tabKa === 'string') {
            activityTableLists[
              parseInt(this.state.tabKa.split('/')[0])
            ].tableName = value.remark
          } else {
            activityTableLists[this.state.tabKa].tableName = value.remark
          }
          this.setState(
            {
              activityTableList: activityTableLists,
              visible: false
            },
            () => {
              message.success('修改成功。')
            }
          )
          return
        }
        activityTableLists.push({
          tableName: value.remark,
          activityProductDtoList: []
        })
        this.setState(
          {
            activityTableList: activityTableLists,
            visible: false
          },
          () => {
            message.success('添加成功。')
          }
        )
      }
    })
  }
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRows })
  }
  adds = () => {
    let _add = [...this.state.add]
    if (_add.length > 4) {
      message.warning('不得超过五个。')
      return
    }
    _add.push('')
    this.setState(
      {
        add: _add
      },
      () => {
        console.log(this.state.add)
      }
    )
  }
  onCha = (e, index) => {
    let _add = [...this.state.add]
    _add[index] = e.target.value
    this.setState({
      add: _add
    })
  }
  render() {
    const {
      form: { getFieldDecorator, getFieldValue }
    } = this.props
    const { detail, visible } = this.state

    const checkContent = (_, value, callback) => {
      if (value.toHTML() === '<p></p>') {
        callback('请输入内容')
        return
      }
      callback()
    }
    const checkMainImages = (_, value, callback) => {
      if (!value) {
        callback('请上传图片')
        return
      }
      callback()
    }

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传照片</div>
      </div>
    )
    const rowSelection = {
      selectedRows: this.state.selectedRows,
      onChange: this.onSelectChange
    }

    const renderPic = () => {
      if (this.state.picUrl) {
        return (
          <img
            src={this.state.picUrl}
            style={{ width: 100, height: 100 }}
            alt=""
          />
        )
      }
      if (this.state.detail.picUrl) {
        return (
          <img
            src={this.state.detail.picUrl}
            style={{ width: 100, height: 100 }}
            alt=""
          />
        )
      }
      return uploadButton
    }

    const formItems = this.state.add.map((k, index) => {
      return (
        <Form.Item label={'输入腰封素材id'} required={false} key={index}>
          <Input
            placeholder="请输入"
            style={{ width: '60%', marginRight: 8 }}
            onChange={e => this.onCha(e, index)}
            value={k}
          />
          {this.state.add.length > 1 ? (
            <Icon
              className="dynamic-delete-button"
              type="minus-circle-o"
              onClick={() => this.remove(index)}
              style={{
                marginRight: 15,
                color: '#5476F0',
                fontSize: 16
              }}
            />
          ) : null}
          {this.state.add.length - 1 === index ? (
            <Icon
              className="dynamic-delete-button"
              type="plus-circle"
              onClick={() => this.adds()}
              style={{
                color: '#5476F0',
                fontSize: 16
              }}
            />
          ) : null}
        </Form.Item>
      )
    })
    const { data } = this.state

    return (
      <PageHeaderWrapper>
        {/* {this.renderRouterWillLeave()} */}
        <Spin spinning={false}>
          <Card bordered={false}>
            <Form {...formItemLayout}>
              <CustomCard title="主题头图" />
              <LZFormItem
                label="活动名称"
                field="activityName"
                getFieldDecorator={getFieldDecorator}
                requiredMessage="活动名称不能为空"
                initialValue={data && data.activityName}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              <LZFormItem
                label="页面名称"
                field="pageName"
                getFieldDecorator={getFieldDecorator}
                requiredMessage="页面名称不能为空"
                initialValue={data && data.pageName}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              <LZFormItem
                label="背景色"
                field="activityBackgroundColor"
                getFieldDecorator={getFieldDecorator}
                requiredMessage="背景色不能为空"
                initialValue={data && data.activityBackgroundColor}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              <LZFormItem
                label="输入标题素材id"
                field="titleMaterialId"
                getFieldDecorator={getFieldDecorator}
                requiredMessage="输入标题素材id不能为空"
                initialValue={data && data.titleMaterialId}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              <CustomCard title="活动时间" />
              <LZFormItem
                label="活动时间"
                field="activityTime"
                getFieldDecorator={getFieldDecorator}
                initialValue={data && data.activityTime}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              <LZFormItem
                label="活动时间背景"
                field="activityTimeColor"
                getFieldDecorator={getFieldDecorator}
                initialValue={data && data.activityTimeColor}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              <CustomCard title="券/活动入口" />
              <LZFormItem
                label="配置活动"
                field="activeEnable"
                getFieldDecorator={getFieldDecorator}
                initialValue={(data && data.activeEnable) || false}
              >
                <Radio.Group>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </Radio.Group>
              </LZFormItem>
              <CustomCard title="豆腐块配置" />
              <LZFormItem
                label="输入豆腐块素材id"
                field={`tofuCubes[${0}]`}
                getFieldDecorator={getFieldDecorator}
                initialValue={data && data.tofuCubes && data.tofuCubes[0]}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              <LZFormItem
                label="输入豆腐块素材id"
                field={`tofuCubes[${1}]`}
                getFieldDecorator={getFieldDecorator}
                initialValue={data && data.tofuCubes && data.tofuCubes[1]}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              <CustomCard title="轮播图" />
              <LZFormItem
                label="背景色配置"
                field="carouselBackgroundColor"
                getFieldDecorator={getFieldDecorator}
                initialValue={data && data.carouselBackgroundColor}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              {formItems}
              <CustomCard title="商品" />
              <LZFormItem
                label="Tab底色配置"
                field="tableBackgroundColor"
                getFieldDecorator={getFieldDecorator}
                initialValue={data && data.tableBackgroundColor}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              <LZFormItem
                label="Tab按钮色配置"
                field="buttonBackgroundColor"
                getFieldDecorator={getFieldDecorator}
                initialValue={data && data.buttonBackgroundColor}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              <Form.Item label={'Tab及商品配置'} required={false}>
                <Fragment>
                  <Button onClick={() => this.handlePreview('新增')}>
                    新增Tab
                  </Button>
                  <Button onClick={() => this.handlePreview('修改')}>
                    修改Tab
                  </Button>
                  <Popconfirm
                    title="确定要删除吗？"
                    onConfirm={() => this.onDelet()}
                  >
                    <Button>删除Tab</Button>
                  </Popconfirm>
                </Fragment>
              </Form.Item>
              <Tabs
                defaultActiveKey={0}
                onChange={this.callback}
                style={{ width: 900 }}
              >
                {this.state.activityTableList.map((item, val) => {
                  return (
                    <TabPane tab={item.tableName} key={val}>
                      <Button onClick={this.handlePreviewCommodity}>
                        新增产品
                      </Button>
                      <Table
                        columns={[
                          {
                            title: '商品ID',
                            dataIndex: 'productId',
                            align: 'center',
                            render: text => <CopyToClipboard text={text} />
                          },
                          {
                            title: '商品名称',
                            dataIndex: 'productName',
                            align: 'center'
                          },
                          {
                            title: '商品价格',
                            dataIndex: 'price',
                            align: 'center',
                            width: 100
                          },
                          {
                            title: '操作',
                            align: 'center',
                            render: (value, row, index) => (
                              <Popconfirm
                                title="确定要删除吗？"
                                onConfirm={() => this.onDeletChild(index)}
                              >
                                <Button type="link">删除</Button>
                              </Popconfirm>
                            )
                          }
                        ]}
                        dataSource={item.activityProductDtoList || []}
                        style={{ marginTop: 20, width: 800 }}
                        rowKey={record => record.skuId}
                        pagination={false}
                      />
                    </TabPane>
                  )
                })}
              </Tabs>
              <CustomCard title="查看更多" style={{ marginTop: 20 }} />
              <LZFormItem
                label="按钮素材id"
                field="bottomMaterialId"
                getFieldDecorator={getFieldDecorator}
                initialValue={data && data.bottomMaterialId}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              <CustomCard title="活动说明" />
              <LZFormItem
                label="背景色"
                field="descriptionBackgroundColor"
                getFieldDecorator={getFieldDecorator}
                initialValue={data && data.descriptionBackgroundColor}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              <LZFormItem
                label="活动说明"
                field="activityDescription"
                getFieldDecorator={getFieldDecorator}
                initialValue={BraftEditor.createEditorState(
                  data && data.activityDescription
                )}
              >
                <BraftEditor
                  style={{
                    border: '1px solid #d1d1d1',
                    borderRadius: 5,
                    backgroundColor: '#fff'
                  }}
                  contentStyle={{
                    height: 500,
                    boxShadow: 'inset 0 1px 3px rgba(0,0,0,.1)'
                  }}
                  excludeControls={['emoji', 'clear', 'blockquote', 'code']}
                  media={{ uploadFn: bfUploadFn }}
                />
              </LZFormItem>
              <CustomCard title="搜索引导" />
              <LZFormItem
                label="素材id"
                field="searchMaterialId"
                getFieldDecorator={getFieldDecorator}
                initialValue={data && data.searchMaterialId}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              <CustomCard title="品牌背书" />
              <LZFormItem
                label="素材id"
                field="footerMaterialId"
                getFieldDecorator={getFieldDecorator}
                initialValue={data && data.footerMaterialId}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
              <FormItem>
                <Row>
                  <Col span={24} style={{ textAlign: 'center' }}>
                    <Button
                      style={{ marginLeft: 8 }}
                      onClick={this.handleCancel}
                    >
                      取消
                    </Button>
                    <Button
                      type="primary"
                      htmlType="submit"
                      onClick={this.handleSubmit}
                    >
                      确定
                    </Button>
                  </Col>
                </Row>
              </FormItem>
            </Form>
          </Card>
        </Spin>
        <Modal
          visible={visible}
          onCancel={this.handleImgCancel}
          onOk={this.onOk}
          title={this.state.title}
          destroyOnClose
        >
          <Form {...formItemLayoutModal}>
            <Form.Item label="Tab标签名称">
              {this.props.form.getFieldDecorator('remark', {
                // rules: [{ required: true, message: '请输入Tab标签名称' }],
                initialValue:
                  this.state.title === '新增'
                    ? undefined
                    : typeof this.state.tabKa === 'string'
                    ? (this.state.activityTableList.length &&
                        this.state.activityTableList[
                          parseInt(this.state.tabKa.split('/')[0])
                        ].tableName) ||
                      undefined
                    : (this.state.activityTableList.length &&
                        this.state.activityTableList[this.state.tabKa]
                          .tableName) ||
                      undefined
              })(<Input placeholder="请输入" />)}
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          visible={this.state.visibleCommodity}
          title="选择商品"
          destroyOnClose
          onCancel={this.handleCancelCommodity}
          onOk={this.submit}
          width={1062}
        >
          <Card bordered={false}>
            <Row
              type="flex"
              align="middle"
              gutter={8}
              style={{ marginTop: 10 }}
            >
              <Col>
                <Input
                  style={{ width: 260 }}
                  onChange={this.handleKeyWords}
                  placeholder="请输入"
                  value={this.state.keyWord}
                />
              </Col>
              <Col>
                <Button type="primary" onClick={this.search}>
                  查询
                </Button>
              </Col>
            </Row>
            <Table
              columns={[
                {
                  title: '商品ID',
                  dataIndex: 'productId',
                  align: 'center',
                  render: text => <CopyToClipboard text={text} />
                },
                {
                  title: '商品名称',
                  dataIndex: 'productName',
                  align: 'center'
                },
                {
                  title: '商品价格',
                  dataIndex: 'price',
                  align: 'center',
                  width: 100
                }
              ]}
              rowSelection={rowSelection}
              dataSource={this.state.list}
              style={{ marginTop: 20 }}
              rowKey={record => record.skuId}
              pagination={{
                current: this.state.pageNumber,
                total: this.state.total,
                defaultPageSize: 10,
                onChange: this.onChange,
                showTotal: this.showTotal
              }}
            />
          </Card>
        </Modal>
        <img
          src="https://youserver.com/v2/P1%E6%B4%BB%E5%8A%A8-%E9%85%8D%E7%BD%AE%E5%8C%96%E9%A1%B5%E9%9D%A2%402x.png"
          style={{
            width: 234,
            height: 850,
            position: 'fixed',
            top: 20,
            right: 90
          }}
        />
      </PageHeaderWrapper>
    )
  }
}
export default Publish
